// pages/fpReserve/fpReserve.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageRoot: app.globalData.imageRoot,
    Page_token: 0,
    step_list: [{
        id: 1,
        name: '发起服务',
        img: '',
        time: ''
      },
      {
        id: 2,
        name: '获取需求',
        img: '',
        time: ''
      },
      {
        id: 3,
        name: '线上邀约',
        img: '',
        time: ''
      },
      {
        id: 4,
        name: '邀约面谈',
        img: '',
        time: ''
      },
      {
        id: 5,
        name: '准备签约',
        img: '',
        time: ''
      },
    ],
    select: 2,
    active: 0,
    btnText: '指派人员',
    show: false,
    CloseShow: false,
    lists: [],
    list: [],
    type: '',
    id: '',
    user: {},
    serviceTimes: 0,
    identity: '',
    assignList: [],
    offset: 0
  },
  user(info) {
    var that = this;
    getApp().ports.yhxx({
      id: info
    }).then((res) => {
      var lists = that.data.lists;
      var res = res.data;
      lists.name = res.nickname;
      lists.img = res.avatarUrl;
      lists.phone = res.phone;
      that.data.user = {
        name: res.nickname,
        img: res.avatarUrl,
        phone: res.phone,
        no: lists.no,
        count: lists.count,
        createTime: lists.createTime,
        client: lists.client
      }
      that.setData({
        lists: lists,
        user: encodeURIComponent(JSON.stringify(that.data.user))
      })
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  userInfo(user) {
    var that = this;
    // var list = that.data.list;
    var liky;
    switch (that.data.type) {
      case 1:
        liky = user.foreclosedHouseBookingorderFollowers.filter((p) => {
          return p.marketer
        })
        break;
      case 2:
        liky = user.discountHouseBookingorderFollowers.filter((p) => {
          return p.marketer
        })
        break;
      case 4:
        liky = user.investigationOrderFollowers.filter((p) => {
          return p.marketer
        })
        break;
    }

    let v = [];
    for (let i = 0; i < liky.length; i++) {
      v[i] = liky[i].marketer
    }
    getApp().ports.api27({
      data: v
    }).then((res) => {
      var res = res.data;
      switch (that.data.type) {
        case 1:
          for (let i in user.foreclosedHouse_bookingorder_followers) {
            for (let j in res) {
              if (user.foreclosedHouse_bookingorder_followers[i].marketer == res[j].id) {
                user.foreclosedHouse_bookingorder_followers[i].name = res[j].nickname;
                user.foreclosedHouse_bookingorder_followers[i].img = res[j].avatar_url;
                user.foreclosedHouse_bookingorder_followers[i].phone = res[j].phone;
                var obj = {
                  name: res[j].nickname,
                  phone: res[j].phone,
                  img: res[j].avatar_url,
                  client: user.client,
                  no: user.no,
                  // createTime:user.results[i].createTime
                }
                user.foreclosedHouse_bookingorder_followers[i].url = '../yyDetails/yyDetails?typeId=' + user.foreclosedHouse_bookingorder_followers[i].id + '&type=' + that.data.type + '&user=' + encodeURIComponent(JSON.stringify(obj))
              }
            }
          }
          that.setData({
            list: user.foreclosedHouse_bookingorder_followers
          })
          break;
        case 2:
          for (let i in user.discountHouseBookingorderFollowers) {
            for (let j in res) {
              if (user.discountHouseBookingorderFollowers[i].marketer == res[j].id) {
                user.discountHouseBookingorderFollowers[i].name = res[j].nickname;
                user.discountHouseBookingorderFollowers[i].img = res[j].avatar_url;
                user.discountHouseBookingorderFollowers[i].phone = res[j].phone;
                var obj = {
                  name: res[j].nickname,
                  phone: res[j].phone,
                  img: res[j].avatar_url,
                  client: user.client,
                  no: user.no,
                  // createTime:user.results[i].createTime
                }
                user.discountHouseBookingorderFollowers[i].url = '../yyDetails/yyDetails?typeId=' + user.discountHouseBookingorderFollowers[i].id + '&type=' + that.data.type + '&user=' + encodeURIComponent(JSON.stringify(obj))
              }
            }
          }
          that.setData({
            list: user.discountHouseBookingorderFollowers
          })
          break;
        case 4:
          for (let i in user.investigationOrderFollowers) {
            for (let j in res) {
              if (user.investigationOrderFollowers[i].marketer == res[j].id) {
                user.investigationOrderFollowers[i].name = res[j].nickname;
                user.investigationOrderFollowers[i].img = res[j].avatar_url;
                user.investigationOrderFollowers[i].phone = res[j].phone;
                var obj = {
                  name: res[j].nickname,
                  phone: res[j].phone,
                  img: res[j].avatar_url,
                  client: user.client,
                  no: user.no,
                  // createTime:user.results[i].createTime
                }
                user.investigationOrderFollowers[i].url = '../yyDetails/yyDetails?typeId=' + user.investigationOrderFollowers[i].id + '&type=' + that.data.type + '&user=' + encodeURIComponent(JSON.stringify(obj))
              }
            }
          }
          that.setData({
            list: user.investigationOrderFollowers
          })
          break;
      }
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  api(data) {
    var that = this;
    var statuss = ['待审核', '待上架', '出售中', '已出售'];
    var type = that.data.type;
    var step_list = that.data.step_list;
    var obj = [];
    if (type == 1) {
      getApp().ports.fpyy({ //优选
        data: data
      }).then((res) => {
        var res = res.data;
        that.user(res.client)
        // that.userInfo(res)
        for (var i = 0; i < res.foreclosedHouseBookingorderFollowers.length; i++) {
          var createTime = app.timeFormat(res.foreclosedHouseBookingorderFollowers[i].createTime, false, true);
          var getDemandTime = app.timeFormat(res.foreclosedHouseBookingorderFollowers[i].getDemandTime, false, true);
          var olInviteTime = app.timeFormat(res.foreclosedHouseBookingorderFollowers[i].olInviteTime, false, true);
          var interviewTime = app.timeFormat(res.foreclosedHouseBookingorderFollowers[i].interviewTime, false, true);
          var beforeSignTime = app.timeFormat(res.foreclosedHouseBookingorderFollowers[i].beforeSignTime, false, true);
          obj.push({})
          obj[i] = [{
            id: 1,
            time: createTime,
            name: step_list[0].name
          }, {
            id: 2,
            time: getDemandTime,
            name: step_list[1].name
          }, {
            id: 3,
            time: olInviteTime,
            name: step_list[2].name
          }, {
            id: 4,
            time: interviewTime,
            name: step_list[3].name
          }, {
            id: 5,
            time: beforeSignTime,
            name: step_list[4].name
          }];
          res.foreclosedHouseBookingorderFollowers[i].step_list = obj[i]
        }
        res.count = res.foreclosedHouseBookingorderFollowers.length;
        res.status = res.foreclosedHouse.status
        res.foreclosedHouse.marketPriceYuan = Math.floor((res.foreclosedHouse.marketPriceYuan / 10000));
        res.foreclosedHouse.priceYuan = Math.floor((res.foreclosedHouse.priceYuan / 10000));
        switch (res.stage) {
          case '变卖':
            res.stage = '秒杀'
            break;
          case '一拍':
            res.stage = '一轮'
            break;
          case '二拍':
            res.stage = '二轮'
            break;
        }
        switch (res.status) {
          case '拍卖中':
            res.status = '进行中'
            break;
          case '已流拍':
            res.status = '已结束'
            break;
        }
        res.tags = [{
          name: res.foreclosedHouse.builtUpAreaSquareCentimeter + '㎡'
        }, {
          name: res.foreclosedHouse.discountRate + '折'
        }, {
          name: res.foreclosedHouse.stage
        }]
        res.url = '../details/details?id=' + res.foreclosedHouse.id + '&status=0'
        res.time = (app.timeFormat(res.foreclosedHouse.startTime)||'') + '-' + (app.timeFormat(res.foreclosedHouse.endTime)||'');
        that.setData({
          lists: res,
          list: res.foreclosedHouseBookingorderFollowers,
          // house:
        })
        that.recommend(res.client)
      }).catch((e) => {
        console.error('出啥错了？', e, '------');
      });
    } else if (type == 2) {
      getApp().ports.zkyy({ //zk
        data: data
      }).then((res) => {
        var res = res.data;
        that.user(res.client)
        // that.userInfo(res)
        // res.discountHouseBookingorderFollowers.forEach(item=>{
        //   item.step_list = step_list
        // })
        for (var i = 0; i < res.discountHouseBookingorderFollowers.length; i++) {
          var createTime = app.timeFormat(res.discountHouseBookingorderFollowers[i].createTime, false, true);
          var getDemandTime = app.timeFormat(res.discountHouseBookingorderFollowers[i].getDemandTime, false, true);
          var olInviteTime = app.timeFormat(res.discountHouseBookingorderFollowers[i].olInviteTime, false, true);
          var interviewTime = app.timeFormat(res.discountHouseBookingorderFollowers[i].interviewTime, false, true);
          var beforeSignTime = app.timeFormat(res.discountHouseBookingorderFollowers[i].beforeSignTime, false, true);
          obj.push({})
          obj[i] = [{
            id: 1,
            time: createTime,
            name: step_list[0].name
          }, {
            id: 2,
            time: getDemandTime,
            name: step_list[1].name
          }, {
            id: 3,
            time: olInviteTime,
            name: step_list[2].name
          }, {
            id: 4,
            time: interviewTime,
            name: step_list[3].name
          }, {
            id: 5,
            time: beforeSignTime,
            name: step_list[4].name
          }];
          res.discountHouseBookingorderFollowers[i].step_list = obj[i]
        }
        res.count = res.discountHouseBookingorderFollowers.length;
        res.status = statuss[res.status]
        res.url = '../details/details?id=' + res.discountHouse.id + '&status=1'
        res.discountHouse.banner = that.data.imageRoot + res.discountHouse.banner
        if (res.discountHouse.tagsstr) {
          let tags = [];
          res.discountHouse.tagsstr.split(",").forEach(item => {
            tags.push({name: item})
          })
          res.discountHouse.tags = tags;
        }
        that.setData({
          lists: res,
          list: res.discountHouseBookingorderFollowers,
        })
        that.recommend(res.client)
      }).catch(() => {
        console.error('出啥错了？');
      });
    } else if (type == 4) { //尽调
      getApp().ports.jdyy({
        data: data
      }).then((res) => {
        var res = res.data;
        that.user(res.client)
        // that.userInfo(res)
        for (var i = 0; i < res.investigationOrderFollowers.length; i++) {
          var createTime = app.timeFormat(res.investigationOrderFollowers[i].createTime, false, true);
          var getDemandTime = app.timeFormat(res.investigationOrderFollowers[i].getDemandTime, false, true);
          var olInviteTime = app.timeFormat(res.investigationOrderFollowers[i].olInviteTime, false, true);
          var interviewTime = app.timeFormat(res.investigationOrderFollowers[i].interviewTime, false, true);
          var finishTime = app.timeFormat(res.investigationOrderFollowers[i].finishTime, false, true);
          obj.push({})
          obj[i] = [{
            id: 1,
            time: createTime,
            name: step_list[0].name
          }, {
            id: 2,
            time: getDemandTime,
            name: step_list[1].name
          }, {
            id: 3,
            time: olInviteTime,
            name: step_list[2].name
          }, {
            id: 4,
            time: interviewTime,
            name: step_list[3].name
          }, {
            id: 5,
            time: finishTime,
            name: step_list[4].name
          }];
          res.investigationOrderFollowers[i].step_list = obj[i]

        }
        res.foreclosedHouse.marketPriceYuan = Math.floor((res.foreclosedHouse.marketPriceYuan / 10000));
        res.foreclosedHouse.priceYuan = Math.floor((res.foreclosedHouse.priceYuan / 10000));
        res.tags = [{
          name: res.foreclosedHouse.builtUpAreaSquareCentimeter + '㎡'
        }, {
          name: res.rate + '折'
        }, {
          name: res.foreclosedHouse.status
        }]
        res.time = (app.timeFormat(res.foreclosedHouse.startTime)||'') + '-' + (app.timeFormat(res.foreclosedHouse.endTime)||'')
        res.count = res.investigationOrderFollowers.length;
        res.status = statuss[res.status]
        res.url = '../details/details?id=' + res.foreclosedHouse.id + '&status=0'
        that.recommend(res.client)
        that.setData({
          lists: res,
          list: res.investigationOrderFollowers
        })
      }).catch(() => {
        console.error('出啥错了？');
      });
    }
  },
  recommend(id) {
    var that = this;
    app.ports.api40({
      data: {pk: id}
    }).then((res) => {
      that.data.comUser = [];
      that.data.comUser[1] = {name: res.data.first.nickname};
      that.data.comUser[2] = {name: res.data.second.nickname};
      that.setData({
        comUser: that.data.comUser
      })
    }).catch(() => {
      console.error("获取邀请关系报错了！")
    })
  },
  gd() {
    var that = this;
    var type = that.data.type
    var data = {};
    if (type == 1) {
      data.foreclosedHouseBookingorderId = that.data.id
      getApp().ports.api3({
        data: data
      }).then((res) => {
        var res = res.data;
      }).catch(() => {
        console.error('出啥错了？');
      });
    } else if (type == 2) {
      data.discountHouseBookingorderId = that.data.id;
      getApp().ports.api7({
        data: data
      }).then((res) => {
        var res = res.data;
      }).catch(() => {
        console.error('出啥错了？');
      });
    } else if (type == 4) {
      data.investigationOrderId = that.data.id
      getApp().ports.api17({
        data: data
      }).then((res) => {
        var res = res.data;
      }).catch(() => {
        console.error('出啥错了？');
      });
    }
  },
  // assign() { //指派人列表
  //   console.log('222', wx.getStorageSync('userId'))
  //   getApp().ports.assign({
  //     id: wx.getStorageSync('userId')
  //   }).then((res) => {

  //   }).catch(() => {
  //     console.error('出啥错了？');
  //   });
  // },
  designee(e) { //被选中的指派人
    var that = this;
    var type = Number(that.data.type);
    var data = {
      marketer: e.currentTarget.dataset.id
    };
    switch (type) {
      case 1:
        data.foreclosedHouseBookingorderId = that.data.id
        getApp().ports.fpgd({ //放盘
          data: data
        }).then((res) => {
          var res = res.data;
          wx.showToast({
            title: '指派成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            CloseShow: false
          })
        }).catch(() => {
          console.error('出啥错了？');
        });
        break;
      case 2:
        data.discountHouseBookingorderId = that.data.id
        getApp().ports.zkgd({ //放盘
          data: data
        }).then((res) => {
          var res = res.data;
          wx.showToast({
            title: '指派成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            CloseShow: false
          })
        }).catch(() => {
          console.error('出啥错了？');
        });
        break;
      case 4:
        data.investigationOrderId = that.data.id
        getApp().ports.jdgd({ //尽调
          data: data
        }).then((res) => {
          var res = res.data;
          wx.showToast({
            title: '指派成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            CloseShow: false
          })
        }).catch(() => {
          console.error('出啥错了？');
        });
        break;
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var titles = ['', '优选预约详情', '折扣预约详情', '', '尽调预约详情', '', '']
    wx.setNavigationBarTitle({
      title: titles[Number(options.type)]
    })
    console.log(options);
    var data = {
      id: options.id
    }
    that.setData({
      type: Number(options.type),
      id: options.id,
      identity: wx.getStorageSync('identity')
    })
    that.api(data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

 
  navTo: function (e) {
    var that = this;
    var url = e.currentTarget.dataset.url;
    var serviceTimes = that.data.serviceTimes;
    // if(serviceTimes == 0){
    //   serviceTimes += 1;
    // this.gd();
    wx.navigateTo({
      url: url,
    })
    // }else{
    //   wx.showToast({
    //     title: '您已发起过此订单的服务',
    //     icon:'none'
    //   })
    //   return
    // }

    that.setData({
      serviceTimes: serviceTimes
    })
  },
  step(e) {
    var that = this;
    if (e.detail == 1) {
      that.setData({
        active: e.detail
      })
    }
  },
  showPopup() {
    this.userAdmin()
    this.setData({
      CloseShow: true,
      offset: 0
    });
  },
  activeBtn() {
    var that = this;

  },
  onClickShow() {
    this.setData({
      show: true
    });
  },

  onClickHide() {
    this.setData({
      show: false
    });
  },

  noop() {},
  CloseHide() {
    this.setData({
      CloseShow: false
    })
  },
  userAdmin(data) {
    console.log('指派')
    var that = this;
    var assignList = [];
    let userId = wx.getStorageSync('userId')
    var identitys = ['商户管理员', '商户总经理'];
    if (wx.getStorageSync('identity') == '市场经理') { //判断是否是以上几个身份
      var params = {creatorId: userId}
      getApp().ports.api46({data: params}).then((data) => {
        var data = data.data;
        
        // var results = data.results;
        // var results = data.results.filter((fil) => {
        //   return fil.creator_id ==  userId
        // })
        // var v = {}
        // for(let i in results){
        //   v = results[i]
        // }
        // TODO 这块蒙了  应该是获取多个组下的所有市场专员
        if (data) { //如果有组且组里有人的话就显示组里的市场专员

          // 获取所有组id
          let groupIds = data.results.map(re => {return re.id})
          let params = {
            groupIds: groupIds,
            roleIds: [5, 7]
          }
          getApp().ports.groupUser({
            data: params
          }).then((res) => {
            // console.log(res, "======1111")
            that.setData({
              assignList: res.data.results
            })
          });

          // console.log(data, '组别')
          // // 感觉这个接口是获取组下的人员 激活角色是 5，7
          // getApp().ports.zhipai({
          //   id: v.id
          // }).then((res) => {
          //   var res = res.data;
          //   res.user_set.forEach((user) => {
          //     getApp().ports.yhxx({ //指派人员列表
          //       data: {},
          //       id: user.id
          //     }).then((obj) => {
          //       var obj = obj.data;
          //       var ids = ['3cbc8151-8920-4e93-8813-59d4d2768d2f','444ff74c-3ac6-4f49-8819-de44c10873a3'];
          //       if (ids.includes(obj.active_role_id)) {
          //         assignList.push(obj)
          //       }
          //       that.setData({
          //         assignList: assignList
          //       })
          //     }).catch(() => {
          //       console.error('出啥错了？');
          //     });
          //   })
          // })  
        } else { //否则就全部的市场专员  
          let data = {
            // active_role_id: '5',
            roleIds: '5',
            page_size: 20,
            page_token: that.data.offset
          }
          getApp().ports.api42({
            data
          }).then((res) => {
            var res = res.data;
            console.log(res)
            // res.results.forEach((item) => {
            //   assignList.push(item)
            // })
            that.setData({
              assignList: res.results,
              total_size: res.results.total
            })
          })
        }
      })
    } else if (wx.getStorageSync('identity') == '合伙经理') {
      console.log('合伙人·经理·')
      //  逻辑等于市场经理有组的情况
      var params = {creatorId: userId}
      getApp().ports.api46({data: params}).then((data) => {
        var data = data.data;
        if (data) {
          // 获取所有组id
          let groupIds = data.results.map(re => {return re.id})
          let params = {
            groupIds: groupIds,
            roleIds: [5, 7]
          }
          getApp().ports.groupUser({
            data: params
          }).then((res) => {
            // console.log(res, "======1111")
            that.setData({
              assignList: res.data.results
            })
          });
          // data.results.forEach((item) => {
          //   getApp().ports.zhipai({
          //     id: item.id
          //   }).then((res) => {
          //     var res = res.data;
          //     res.user_set.forEach((user) => {
          //       getApp().ports.yhxx({ //指派人员列表
          //         data: {},
          //         id: user.id
          //       }).then((obj) => {
          //         var obj = obj.data;
          //         var ids = ['3cbc8151-8920-4e93-8813-59d4d2768d2f', '444ff74c-3ac6-4f49-8819-de44c10873a3'];
          //         if (ids.includes(obj.active_role_id)) {
          //           console.log(obj)
          //           assignList.push(obj)
          //         }
          //         that.setData({
          //           assignList: assignList
          //         })
          //       }).catch(() => {
          //         console.error('出啥错了？');
          //       });
          //     })
          //   })
          // })
        } else {
          console.log('111')
        }
      })
    }else if(identitys.includes(wx.getStorageSync('identity'))){
      let data = {
        // active_role_id: '444ff74c-3ac6-4f49-8819-de44c10873a3',
        roleIds: '5',
        page_size: 20,
        page_token: that.data.offset
      }
      getApp().ports.api42({
        data
      }).then((res) => {
        var res = res.data;
        console.log(res)
        // res.results.forEach((item) => {
        //   assignList.push(item)
        // })
        that.setData({
          assignList: res.results,
          total_size: res.results.total
        })
      })
    }
  },
  assignEnd() {
    var that = this;

    if (that.data.total_size > that.data.assignList.length) {
      that.data.offset += 1
      that.userAdmin()
    }
  }
})